<template>
  <el-dialog
    v-model="visible"
    :title="$t('order.orderShipping')"
    :close-on-click-modal="false"
    width="760px"
    class="components-delivery-update"
    @close="dialogClose"
  >
    <div class="mod-order-orderInfo">
      <el-table
        ref="multipleTableRef"
        :data="dataList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="onSelectSome"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="onCheckSelectable"
        />
        <el-table-column
          :label="$t('home.product')"
          fit
        >
          <template #default="scope">
            {{ scope.row.prodName }}
            <div
              v-if="
                scope.row.returnMoneySts !== null &&
                  scope.row.returnMoneySts > 0 &&
                  scope.row.returnMoneySts < 6
              "
              class="order-status"
            >
              {{ $t("order.reimburse") }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="prodCount"
          :label="$t('order.canShipQuantity')"
          width="100"
        />
        <el-table-column
          prop="status"
          :label="$t('product.status')"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            <el-tag
              v-if="
                scope.row.returnMoneySts !== null &&
                  scope.row.returnMoneySts < 6 &&
                  scope.row.returnMoneySts > 0
              "
              type="danger"
            >
              {{
                [
                  "",
                  $t("order.buyerApplication"),
                  $t("order.sellerAccepts"),
                  $t("order.selShipment"),
                  $t("order.sellerReceipt"),
                  $t("order.refundsuccessfully"),
                ][scope.row.returnMoneySts]
              }}
            </el-tag>
            <el-tag
              v-else-if="scope.row.status !== 0 && scope.row.status !== -1"
              type="warning"
            >
              {{ $t("order.partialDelivery") }}
            </el-tag>
            <el-tag
              v-else-if="scope.row.status === 0"
            >
              {{
                $t("order.shipmentCompleted")
              }}
            </el-tag>
            <el-tag
              v-else-if="scope.row.status === -1"

              type="warning"
            >
              {{ $t("order.toBeShipped") }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="changeNum"
          class="medius-line-height"
          :label="$t('order.numberOfShipments')"
          fit
        >
          <template #default="scope">
            <el-input-number
              v-model="scope.row.changeNum"
              :disabled="scope.row.prodCount <= 0"

              :precision="0"
              :min="0"
              :max="scope.row.prodCount"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :label-width="$t('language') === '简体中文' ? '100px' : '200px'"
      @submit.prevent
    >
      <div class="detail-cont">
        <div class="detail01">
          <div class="text-width">
            <el-form-item
              :label="$t('order.waitForDelivery')"
              class="newline"
            >
              <span>{{ $t("order.delType") }}:{{
                [$t("order.expressDelivery"),
                 $t("order.selfMention"),
                 $t("order.noNeedRequired"),
                 $t("order.sameCityDelivery")
                ][initDeliveryType - 1]
              }}</span>
            </el-form-item>
            <el-form-item>
              <span>{{ $t("publics.addressee") }}：{{
                dataForm.userAddrOrder.receiver
              }}</span>
            </el-form-item>
            <el-form-item>
              <span>{{ $t("distribution.phoneNum") }}：{{
                dataForm.userAddrOrder.mobile
              }}</span>
            </el-form-item>
            <el-form-item>
              <span>{{ $t("publics.deliveryAddr") }}：{{
                dataForm.userAddrOrder.province
              }}{{ dataForm.userAddrOrder.city
              }}{{ dataForm.userAddrOrder.area
              }}{{ dataForm.userAddrOrder.addr }}</span>
            </el-form-item>
          </div>
        </div>
      </div>
      <el-form-item :label="$t('order.deliveryMethod') + '：'">
        <el-radio-group
          v-model="dataForm.tempDeliveryType"
          @change="onClear()"
        >
          <el-radio
            :label="1"
            :disabled="dataForm.deliveryType === 4"
          >
            {{
              $t("order.ordinaryExpress")
            }}
          </el-radio>
          <el-radio
            :label="3"
            :disabled="dataForm.deliveryType === 4 || isPartialDelivery || isDisableNoCourier"
          >
            {{
              $t("order.noNeedRequired")
            }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!--配送方式 线上 线下-->
      <el-form-item
        v-if="dataForm.tempDeliveryType === 1"
        :label="$t('order.delType') + '：'"
        style="text-align: left;"
      >
        <el-radio-group v-model="dataForm.deliveryType">
          <el-radio
            :label="0"
            :disabled="isPrint === 0"
          >
            {{
              $t("order.onlineDelivery")
            }}
          </el-radio>
          <el-radio
            :label="1"
          >
            {{
              $t("order.selfDelivery")
            }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!--自行联系快递-->
      <div v-if="dataForm.deliveryType === 1">
        <el-form-item :label="$t('order.courierCompany') + '：'">
          <SelectLazy
            v-model="dataForm.dvyId"
            :placeholder="$t('tip.select')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('order.trackingNumber') + '：'"
          prop="dvyFlowId"
        >
          <el-input
            v-model="dataForm.dvyFlowId"
            width="80"
            maxlength="20"
            show-word-limit
            :placeholder="$t('order.trackingNumber')"
          />
        </el-form-item>
      </div>
      <!--线上发货-->
      <div v-if="dataForm.deliveryType === 0">
        <el-form-item
          :label="$t('order.courierCompany') + '：'"
          prop="deliveryCompanyType"
        >
          <div class="part-form-delivery">
            <el-select
              v-model="dataForm.deliveryCompanyType"
              :placeholder="$t('tip.select')"
              @change="onDeliveryCompanyTypeChange"
            >
              <el-option
                v-for="item in outletConfigList"
                :key="item.deliveryCompanyType"
                :label="item.deliveryCompanyName"
                :value="item.deliveryCompanyType"
              />
            </el-select>
            <div
              v-if="deliveryCompanyType.isConfig === 0"
              class="lb"
            >
              <el-button
                type="primary"
                link
                @click="onToConfigOutlet"
              >
                {{ $t('order.toOpen') }}
              </el-button>
              <span
                class="vertical"
              />
              <el-button
                type="primary"
                link
                @click="onGetOutletConfigList"
              >
                {{ $t('admin.refresh') }}
              </el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          v-if="deliveryCompanyType.isConfig === 1"
          :label="$t('order.deliveryAddress') + '：'"
          prop="outletConfigId"
        >
          <el-select
            v-model="dataForm.outletConfigId"
            :placeholder="$t('tip.select')"
            style="width: 330px"
          >
            <el-option
              v-for="item in deliveryCompanyType.shopAddrList"
              :key="item.outletConfigId"
              :label="item.printAddr"
              :value="item.outletConfigId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="deliveryCompanyType.isConfig === 1"
          :label="$t('order.deliveryPrintType') + '：'"
        >
          <el-radio-group v-model="isPrint">
            <el-radio
              :label="1"
            >
              {{
                $t("order.printInfo")
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="deliveryCompanyType.isConfig === 1"
          :label="$t('order.printer') + '：'"
          prop="printerId"
        >
          <div class="part-form-delivery">
            <el-select
              v-model="dataForm.printerId"
              :placeholder="$t('tip.select')"
            >
              <el-option
                v-for="item in printerList"
                :key="item.printerId"
                :label="item.printerName"
                :value="item.printerId"
              />
            </el-select>
            <div
              class="lb"
            >
              <el-button
                type="primary"
                link
                @click="onToConfigPrinter"
              >
                {{ $t('admin.newConstruction') }}
              </el-button>
              <span
                class="vertical"
              />
              <el-button
                type="primary"
                link
                @click="onGetPrinterList"
              >
                {{ $t('admin.refresh') }}
              </el-button>
            </div>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span>
        <span
          class="default-btn"
          @click="visible = false"
        >{{
          $t("crud.filter.cancelBtn")
        }}</span>
        <span
          class="default-btn primary-btn"
          @click="onSubmit()"
        >{{
          $t("crud.filter.submitBtn")
        }}</span>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshOrderAmountUpdate'])

const visible = ref(false)
const dataForm = ref({
  dvyId: '',
  userAddrOrder: {},
  dvyFlowId: '',
  dvyNames: [],
  orderNumber: 0,
  deliveryType: 1,
  tempDeliveryType: 1,
  outletConfigId: null,
  printerId: null,
  deliveryCompanyType: null
})
const deliveryCompanyType = ref({
  deliveryCompanyType: null,
  deliveryCompanyName: null,
  isConfig: null,
  isDefault: null,
  shopAddrList: []
})
const initDeliveryType = ref(1)
const dataList = ref([])
let isSubmit = false
let orderNumber = 0

// 判断是否部分发货
const isPartialDelivery = computed(() => {
  return dataList.value.some(item => item.status !== 0 && item.status !== -1)
})

const init = (order) => {
  dataForm.value.deliveryCompanyType = null
  dataForm.value.printerId = null
  deliveryCompanyType.value.deliveryCompanyType = null
  deliveryCompanyType.value.deliveryCompanyName = null
  deliveryCompanyType.value.isConfig = null
  deliveryCompanyType.value.isDefault = null
  deliveryCompanyType.value.shopAddrList = []
  isSubmit = false
  dataForm.value.userAddrOrder = {}
  visible.value = true
  orderNumber = order.orderNumber
  onClear()
  onGetQuick100()
  onGetOutletConfigList()
  onGetPrinterList()
  // 修改
  http({
    url: http.adornUrl(`/order/delivery/getOrderItemUnDelivery/${order.orderNumber}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dataForm.value.userAddrOrder = data.userAddrOrder
    if (data.dvyType === 2 || data.dvyType === 4) {
      dataForm.value.deliveryType = parseInt(data.dvyType)
    } else {
      dataForm.value.deliveryType = isPrint.value === 1 ? 0 : parseInt(data.dvyType)
    }
    dataForm.value.tempDeliveryType = dataForm.value.deliveryType === 0 || dataForm.value.deliveryType === 1 ? 1 : dataForm.value.deliveryType
    initDeliveryType.value = dataForm.value.deliveryType
    dataList.value = data.orderItems
    dataList.value.forEach(element => {
      element.changeNum = element.prodCount
    })
  })
}
const onDeliveryCompanyTypeChange = (val) => {
  outletConfigList.value.forEach(el => {
    if (el.deliveryCompanyType === val) {
      deliveryCompanyType.value = el
    }
  })
  dataForm.value.outletConfigId = null
}

// 是否禁用"无需快递"选项
const isDisableNoCourier = ref(false)
/**
 * 修改状态
 */
const selectOrderItems = ref([])

const onSelectSome = (val) => {
  selectOrderItems.value = val
  getNoDeliverySts()
}
watch(() => dataList.value, () => {
  getNoDeliverySts()
}, { deep: true })

/**
 * 设置无需快递按钮状态
 */
const getNoDeliverySts = () => {
  let flag = false
  if (dataList.value.length !== selectOrderItems.value.length) {
    flag = true
  }
  for (let i = 0; i < dataList.value.length; i++) {
    const item = dataList.value[i]
    if (item.status != -1 || item.changeNum != item.prodCount) {
      flag = true
      break
    }
  }
  if (flag && dataForm.value.deliveryType === 3) {
    dataForm.value.deliveryType = isPrint.value === 1 ? 0 : parseInt(dataForm.value.deliveryType)
    dataForm.value.tempDeliveryType = dataForm.value.deliveryType === 0 || dataForm.value.deliveryType === 1 ? 1 : dataForm.value.deliveryType
  }
  isDisableNoCourier.value = flag
}
/**
 * 禁用多选按钮
 */
const onCheckSelectable = (row) => {
  return row.status !== 0 && (!row.returnMoneySts || row.returnMoneySts < 0 || row.returnMoneySts > 5)
}
const onClear = () => {
  if (dataForm.value.tempDeliveryType === 3) {
    dataForm.value.deliveryType = 3
  } else if (dataForm.value.tempDeliveryType === 4) {
    dataForm.value.deliveryType = 4
  } else {
    if (isPrint.value === 1) {
      dataForm.value.deliveryType = 0
    } else {
      dataForm.value.deliveryType = 1
    }
  }
  dataForm.value.dvyFlowId = ''
  dataForm.value.dvyId = ''
}
let isTrue = false
let errorInfo = ''

const onCheck = () => {
  isTrue = false
  if (selectOrderItems.value.length <= 0) {
    isTrue = true
    errorInfo = $t('order.seleOrd')
    return true
  }
  if (dataForm.value.deliveryType === 0) {
    if (dataForm.value.deliveryCompanyType && deliveryCompanyType.value.isConfig === 0) {
      isTrue = true
      errorInfo = '未开通相关物流配置'
      return true
    }
    if (!dataForm.value.deliveryCompanyType) {
      isTrue = true
      errorInfo = $t('order.seleCouCom')
      return true
    }
    if (!dataForm.value.outletConfigId) {
      isTrue = true
      errorInfo = '请选择发货地址'
      return true
    }
    if (!dataForm.value.printerId) {
      isTrue = true
      errorInfo = '请选择打印机'
      return true
    }
  }
  selectOrderItems.value.forEach(element => {
    if (element.prodCount <= 0 || element.prodCount < element.changeNum || element.changeNum <= 0) {
      isTrue = true
      errorInfo = element.prodName + $t('order.numNotZero') + '！'
      return true
    }
    if (element.changeNum <= 0) {
      isTrue = true
      errorInfo = element.prodName + $t('order.numNotZero') + '！'
      return true
    }
    if (element.changeNum == null) {
      isTrue = true
      errorInfo = element.prodName + $t('order.fhNumNotZero') + '！'
      return true
    }
  })
  if (dataForm.value.dvyId === '' && dataForm.value.deliveryType === 1) {
    isTrue = true
    errorInfo = $t('order.seleCouCom')
    return true
  }
  if ((dataForm.value.dvyFlowId === 0 || !dataForm.value.dvyFlowId) && dataForm.value.deliveryType === 1) {
    isTrue = true
    errorInfo = $t('order.entCouNum')
    return true
  }
  const reg = /^[a-zA-Z0-9]{4,30}$/
  if (!reg.test(dataForm.value.dvyFlowId) && dataForm.value.deliveryType === 1) {
    isTrue = true
    errorInfo = $t('order.checkDvyId')
    return true
  }
}

/**
 * 确定事件
 */
const onSubmit = () => {
  onCheck()
  if (isTrue) {
    onErrorMsg(errorInfo)
    return
  }
  if (isSubmit) {
    return
  }
  isSubmit = true
  const freightAmount = 0

  http({
    url: http.adornUrl('/order/delivery/orderItemsDelivery'),
    method: 'put',
    data: http.adornData({
      orderNumber,
      dvyId: dataForm.value.dvyId,
      dvyFlowId: dataForm.value.dvyFlowId,
      freightAmount,
      deliveryType: dataForm.value.tempDeliveryType !== 1 ? dataForm.value.tempDeliveryType : dataForm.value.deliveryType,
      orderAddrId: dataForm.value.orderAddrId,
      outletConfigId: dataForm.value.outletConfigId,
      printerId: dataForm.value.printerId,
      deliveryCompanyType: dataForm.value.deliveryCompanyType,
      selectOrderItems: selectOrderItems.value
    })
  }).then(() => {
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        visible.value = false
        emit('refreshOrderAmountUpdate')
      }
    })
  }).catch(() => {
    isSubmit = false
  })
}
const onErrorMsg = (message) => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}
// 获取网点列表
const outletConfigList = ref([])
const onGetOutletConfigList = () => {
  http({
    url: http.adornUrl('/delivery/outletConfig/listOutletConfig'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    outletConfigList.value = data
    if (deliveryCompanyType.value.deliveryCompanyType !== null) {
      data.forEach(el => {
        if (el.deliveryCompanyType === deliveryCompanyType.value.deliveryCompanyType) {
          deliveryCompanyType.value = el
          dataForm.value.deliveryCompanyType = el.deliveryCompanyType
          el.shopAddrList.forEach(val => {
            if (val.isDefault === 1) {
              dataForm.value.outletConfigId = val.outletConfigId
            }
          })
        }
      })
      return
    }
    data.forEach(el => {
      if (el.isDefault === 1) {
        // 设置选中默认配置
        deliveryCompanyType.value = el
        dataForm.value.deliveryCompanyType = el.deliveryCompanyType
        el.shopAddrList.forEach(val => {
          if (val.isDefault === 1) {
            dataForm.value.outletConfigId = val.outletConfigId
          }
        })
      }
    })
  })
}

const printerList = ref([])
// 获取打印机列表
const onGetPrinterList = () => {
  http({
    url: http.adornUrl('/delivery/printer/listPrinter'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    printerList.value = data
    data.forEach(el => {
      if (el.isDefault === 1) {
        // 设置选中默认配置
        dataForm.value.printerId = el.printerId
      }
    })
  })
}

// 获取快递100配置
const isPrint = ref(0)
const onGetQuick100 = () => {
  http({
    url: http.adornUrl('/sys/pconfig/quick100'),
    method: 'get',
    params: http.adornParams()
  }).then((res) => {
    isPrint.value = res.data ? 1 : 0
  })
}

// 去开通网点
const onToConfigOutlet = () => {
  window.open('/system/delivery/outlet-config/index', '_blank', 'noopener,noreferrer')
}

// 去配置打印机
const onToConfigPrinter = () => {
  window.open('/system/delivery/printer/index', '_blank', 'noopener,noreferrer')
}
defineExpose({ init })
</script>
<style lang="scss" scoped>
.components-delivery-update{
 :deep(.el-input__inner)  {
    border: 1px solid #dcdfe6 !important;
  }
.mod-order-orderInfo {
height: 100%;
width: 100%;
font: 14px Arial, "PingFang SC", "Hiragino Sans GB", STHeiti,
  "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif;
color: #495060;
}
:deep(.element.style)  {
border-top: 1px solid #eeeeee;
border-right: 1px solid #eeeeee;
border-bottom: 1px solid #eeeeee;
}
:deep(.el-input-number--medium)  {
width: 150px;
line-height: 30px;
}
div :deep(.el-input-number--medium .el-input-number__increase) {
border-left: 1px solid #dcdfe6 !important;
}
}
.part-form-delivery {
  display:flex;
  .lb {
    display: flex;
    align-items: center;

    margin-left: 20px;

    .vertical {
      display: inline-block;
      width: 1px;
      height: 10px;
      background: #000;
      margin: 0 6px;
    }
  }
}
</style>
